package com.wywah.core.predicate;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.cloud.gateway.handler.predicate.GatewayPredicate;
import org.springframework.cloud.gateway.handler.predicate.PathRoutePredicateFactory;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.style.ToStringCreator;
import org.springframework.http.server.PathContainer;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.pattern.PathPatternParser;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;

/**
 *
 * @see org.springframework.cloud.gateway.handler.predicate.PathRoutePredicateFactory
 */
@Component
public class CustomServiceRoutePredicateFactory extends AbstractRoutePredicateFactory<CustomServiceRoutePredicateFactory.Config> {



    public CustomServiceRoutePredicateFactory() {
        super(Config.class);
    }

//    @Override
//    public ShortcutType shortcutType() {
//        return ShortcutType.GATHER_LIST_TAIL_FLAG;
//    }

    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList("patterns");
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        PathPatternParser pathPatternParser = new PathPatternParser();
        return new GatewayPredicate(){

            @Override
            public boolean test(ServerWebExchange exchange) {
                Map<String, Object> attributes = exchange.getAttributes();
                System.out.println("-----------");
                PathContainer path = (PathContainer)exchange.getAttributes().computeIfAbsent(ServerWebExchangeUtils.GATEWAY_PREDICATE_PATH_CONTAINER_ATTR,
                        (s) -> PathContainer.parsePath(exchange.getRequest().getURI().getRawPath()));

                String routId = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_PREDICATE_ROUTE_ATTR);
                if(StringUtils.hasText(routId) && routId.startsWith("wywah-")){
                    String replace = routId.replace("wywah-", "");
                    boolean matches = pathPatternParser.parse("/api/" + replace.toLowerCase() + "/**").matches(path);
                    return matches;
                }
                return false;
            }

            @Override
            public Object getConfig() {
                return config;
            }
        };
    }

//    @Validated
    public static class Config {

        public String patterns;

        public Config() {
        }

        public String getPatterns() {
            return patterns;
        }

        public void setPatterns(String patterns) {
            this.patterns = patterns;
        }
    }
}
